<script setup>
import LteModal from "../../../layout/components/LteModal.vue";
import LteAlert from "../../../layout/components/LteAlert.vue";
import LteCheckbox from "../../../layout/components/LteCheckbox.vue";
import LteCheckboxGroup from "../../../layout/components/LteCheckboxGroup.vue";
import { AllRoles } from "../../../apis/system/role";
import { GetUserRoles } from "../../../apis/system/user";
import { reactive, getCurrentInstance } from 'vue'

const instance = getCurrentInstance();

const data = reactive({
    show: false,
    callback: null,
    model: {},
    items: [],
    selected: [],
});

const check = function(model, permissions) {
    instance.refs.refAlert.close();
    return true;
};

const submit = function(e) {
    //执行判断
    if(!check(data.model, data.selected)) {
        return;
    }
    //执行回调
    if(data.callback){
        data.callback(data.selected);
    }
};

const loadItems = function(model) {
    data.items = [];
    data.loading = true;
    AllRoles({page: 0, pageSize: 60}).then((res) => {
        data.items = res.data.result.list;
    }).finally((res) => {
        data.loading = false;
    });
};

const loadSelected = function(model) {
    data.loading = true;
    GetUserRoles({id: model.id}).then((res) => {
        data.selected = [];
        res.data.result.forEach(function(item){
            data.selected.push(item["role_id"]);
        });
    }).finally((res) => {
        data.loading = false;
    });
};

defineExpose({
    open : function(model, callback){
        //设置属性
        data.model = JSON.parse(JSON.stringify(model));
        data.errors = [];
        data.show = true;
        data.callback = callback;
        //设置组件
        instance.refs.refAlert.close();
        //加载数据
        loadItems(data.model);
        loadSelected(data.model);
    },
    close : function(){
        //设置属性
        data.show = false;
    },
    error : function(message){
        //显示弹窗
        instance.refs.refAlert.open('danger', message);
    },
});
</script>

<template>
    <lte-modal v-model="data.show" title="角色">
        <div>
            <div class="row">
                <div class="col-sm">
                    <lte-alert ref="refAlert"></lte-alert>
                </div>
            </div>
            <div class="row">
                <div class="col-sm">
                    <lte-checkbox-group direction="column">
                        <template v-for="item in data.items">
                            <lte-checkbox :value="item.id" v-model="data.selected">{{item.name}}</lte-checkbox>
                        </template>
                    </lte-checkbox-group>
                </div>
            </div>
        </div>
        <template #footer>
            <button class="btn btn-default" @click="data.show = false">取消</button>
            <button class="btn btn-primary float-right" @click="submit">确认</button>
        </template>
    </lte-modal>
</template>

<style scoped></style>